// ------------------------------------------------------------------------------------------
// Licensed by Interprise Solutions.
// http://www.InterpriseSolutions.com
// For details on this license please visit  the product homepage at the URL above.
// THE ABOVE NOTICE MUST REMAIN INTACT.
// ------------------------------------------------------------------------------------------
using System;
using System.Text;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Globalization;
using InterpriseSuiteEcommerceCommon;
using InterpriseSuiteEcommerceControls;
using System.Collections.Generic;
using InterpriseSuiteEcommerceCommon.InterpriseIntegration;
using InterpriseSuiteEcommerceControls.Validators;
using InterpriseSuiteEcommerceCommon.DTO;
using System.Data.SqlClient;
using InterpriseSuiteEcommerceCommon.Extensions;

namespace InterpriseSuiteEcommerce
{
    /// <summary>
    /// Summary description for editaddress.
    /// </summary>
    public partial class editaddress : SkinBase
    {

        #region Variable Declarations

        bool checkOutMode = false;
        String AddressID = String.Empty;
        String AddressTypeString = String.Empty;
        AddressTypes AddressType = AddressTypes.Unknown;

        #endregion

        #region OnInit

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            ResolveQueryStrings();
            PerformPageAccessLogic();

            if (!IsPostBack)
            {
             
                InitializeAddressControls();
                InitializePageContent();

                AddressBookHelpfulTips.SetContext = this;
            }
        }

        #endregion

        #region ResolveQueryStrings

        private void ResolveQueryStrings()
        {
            checkOutMode = CommonLogic.QueryStringBool("checkout");
            AddressID = CommonLogic.QueryStringCanBeDangerousContent("AddressID");
        }

        #endregion

        #region PerformPageAccessLogic

        private void PerformPageAccessLogic()
        {
            if (AppLogic.AppConfigBool("UseSSL"))
            {
                if (AppLogic.OnLiveServer() && CommonLogic.ServerVariables("SERVER_PORT_SECURE") != "1")
                {
                    Response.Redirect(AppLogic.GetStoreHTTPLocation(true) + "changeaddress.aspx?" + CommonLogic.ServerVariables("QUERY_STRING"));
                }
            }

            AddressTypeString = CommonLogic.QueryStringCanBeDangerousContent("AddressType");
            if (AddressTypeString.IndexOf("<script>", StringComparison.InvariantCultureIgnoreCase) != -1)
            {
                throw new ArgumentException("SECURITY EXCEPTION");
            }
            //AddressTypeString is empty if you change language.
            if (AddressTypeString.Length != 0)
            {
                AddressType = (AddressTypes)Enum.Parse(typeof(AddressTypes), AddressTypeString, true);
            }
            if (AddressType == AddressTypes.Unknown)
            {
                AddressType = AddressTypes.Shipping;
                AddressTypeString = "Shipping";
            }
        }

        #endregion

        #region InitializeAddressControls

        private void InitializeAddressControls()
        {

            DisplayCustomerAccountInformation();

        }

        #endregion

        #region InitializePageContent

        private void InitializePageContent()
        {
            pnlCheckoutImage.Visible = checkOutMode;
            CheckoutImage.ImageUrl = AppLogic.LocateImageURL("skins/skin_" + SkinID.ToString() + "/images/step_2.gif");

            btnReturn.Text = AppLogic.GetString("account.aspx.27", SkinID, ThisCustomer.LocaleSetting, true);
            btnReturn.OnClientClick = "self.location='selectaddress.aspx?checkout=" + checkOutMode.ToString() + "&AddressType=" + AddressTypeString + "';return false;";

            string addressType = CommonLogic.QueryStringCanBeDangerousContent("AddressType");
            if (addressType.ToLower() != "shipping")
            {
                AddressControl.showResidenceTypes = false;
            }
            else
            {
                AddressControl.showResidenceTypes = true;
            }

            if (ThisCustomer.IsInEditingMode())
            {
                AppLogic.EnableButtonCaptionEditing(btnReturn, "account.aspx.27");
            }
        }

        #endregion

        #region DisplayCustomerAccountInformation

        private void DisplayCustomerAccountInformation()
        {
            if (!IsPostBack)
            {
                Address theAddress = Address.Get(ThisCustomer, AddressType, AddressID);

                txtContactName.Text    = theAddress.Name;
                AddressControl.street  = theAddress.Address1;      
                AddressControl.city    = theAddress.City;
                AddressControl.state   = theAddress.State;
               
                AddressControl.residenceTypeSelected = theAddress.ResidenceType.ToString();
                AddressControl.countrySelected = theAddress.Country;

                txtPhone.Value         = theAddress.Phone;

                if (AppLogic.AppConfigBool("Address.ShowCounty") && !string.IsNullOrEmpty(theAddress.County))
                {
                    AddressControl.county = theAddress.County;
                }

                string postal = theAddress.PostalCode;

                if (!theAddress.Plus4.IsNullOrEmptyTrimmed())
                {
                    postal = String.Format("{0}-{1}", postal, theAddress.Plus4);
                }

                AddressControl.postal = postal;
               
            }
        }

        #endregion

        #region SaveAddress

        /// <summary>
        /// Saving/Updating of Editted Address
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void btnUpdateAddress_Click(object sender, EventArgs e)
        {

            ThisCustomer.RequireCustomerRecord();

            Address thisAddress = Address.Get(ThisCustomer, AddressType, AddressID);

            string bCityStates = txtCityStates.Text;
            string city = string.Empty;
            string state = string.Empty;

            if (!string.IsNullOrEmpty(bCityStates))
            {
                var _cityState = bCityStates.Split(',');

                if (_cityState.Length > 1)
                {
                    state = _cityState[0].Trim();
                    city = _cityState[1].Trim();
                }
                else
                {
                    city = _cityState[0].Trim();
                    state = string.Empty;
                }

            }
            else
            {
                state = AddressControl.state;
                city = AddressControl.city;
            }

            thisAddress.Name          = txtContactName.Text;
            thisAddress.Address1      = AddressControl.street;
            thisAddress.City          = city;
            thisAddress.State         = state;
            thisAddress.PostalCode    = AddressControl.postal;
            thisAddress.Country       = AddressControl.country;
            thisAddress.Phone         = string.Format("({0}){1}", txtAreaCode.Text, txtPrimaryPhone.Text);

           if (AddressType == AddressTypes.Billing) thisAddress.CardName = txtContactName.Text;
           
            if(AddressType == AddressTypes.Shipping){

                 if (AddressControl.residenceType == ResidenceTypes.Residential.ToString())
                 {
                    thisAddress.ResidenceType = ResidenceTypes.Residential;
                 }else{
                    thisAddress.ResidenceType = ResidenceTypes.Commercial;
                 }
            }

            if (AppLogic.AppConfigBool("Address.ShowCounty")) thisAddress.County = AddressControl.county;

            Address.Update(ThisCustomer, thisAddress);
            Response.Redirect(String.Format("selectaddress.aspx?Checkout={0}&AddressType={1}", checkOutMode.ToString(), AddressType));

        }

        #endregion

        #region Event Handlers

        #region Page_Load

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
        }

        protected override void OnUnload(EventArgs e)
        {
            base.OnUnload(e);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            Response.CacheControl = "private";
            Response.Expires = 0;
            Response.AddHeader("pragma", "no-cache");

            RequireSecurePage();

            SectionTitle = AppLogic.GetString("editaddress.aspx.1", SkinID, ThisCustomer.LocaleSetting, true);

        }

        #endregion

        #endregion
    }
}




